'use strict';

const SwaggerParser = require('swagger-parser');
const utilJson = require('util-json');
const parserLoadRouter = require('./parser-load-router');
const CircularJSON = require('circular-json');
const path = require('path');
const fs = require('fs');
const loadMiddleware = require('./middleware');
const dirLoad = require('./dir-load');

module.exports = function(configJson,app,currentPath,driverConfig,callback){
  //原型扩展
  Function.prototype.getName = function(){
    return this.name || false;
  }

  var routerFileReadActions = [];
  var routerConfig = {
    controllers:{}
  };
  app.holdList = {
    middlewares:[] //加载不启用的中间件
  };

  //加载util
  if(configJson.util && configJson.util.dir.length > 0){
    let result = dirLoad(app ,currentPath, configJson.util, 'util');
    if(result){
      app.utils = result;
    }
  }

  //加载controllers
  if(configJson.controller && configJson.controller.dir.length > 0){
    let result = dirLoad(app ,currentPath, configJson.controller, 'controller');
    if(result){
      for(let k in result){
        result[k].prototype.app = app;
        routerConfig.controllers[k] = new result[k]();
        // routerConfig.controllers[k].say();
      }
    }
  }

  //路由方法加载
  // let RouterFunFilePath = path.join(currentPath,driverConfig.routerFileName);
  // try{
  //   let RouterFunFileExists = fs.existsSync(RouterFunFilePath+'.js');
  //   console.log("%s项目找到路由方法文件", path.basename(currentPath));console.log(RouterFunFilePath);
  //   routerConfig.RouterFun = require(RouterFunFilePath);
  //   routerConfig.RouterFun.name = path.basename(currentPath);
  // }catch(err){
  //   console.log("%s项目没有找到路由方法文件", path.basename(currentPath));
  // }

  //加载handlers
  if(configJson.handler && configJson.handler.dir.length > 0){
    let result = dirLoad(app ,currentPath, configJson.handler, 'handlers');
    routerConfig.handlers = result;
  }


  //*****************************逐个分析并加载中间件和路由
  //获取普通网站配置
  var commonConfig = configJson.http;
  loadMiddleware(app, currentPath, commonConfig.middleware);
  console.log("%s项目开始读取并加载普通站点路由...", path.basename(currentPath));
  if(commonConfig.router && commonConfig.router.file.length > 0){
    routerFileReadActions.push(loadRouter(commonConfig.router));
  }else{
    console.log("%s项目没有找到普通站点路由...", path.basename(currentPath));
  }


  //获取socket相关配置
  var socketConfig = configJson.socket;
  loadMiddleware(app, currentPath, socketConfig.middleware);
  console.log("%s项目开始读取并加载socket路由...", path.basename(currentPath));
  if(socketConfig.router && socketConfig.router.file.length > 0){
    routerFileReadActions.push(loadRouter(socketConfig.router));
  }else{
    console.log("%s项目没有找到socket路由...", path.basename(currentPath));
  }

  //获取任务相关配置
  var agentConfig = configJson.agent;
  loadMiddleware(app, currentPath, agentConfig.middleware);
  console.log("%s项目开始读取并加载任务路由...", path.basename(currentPath));
  if(agentConfig.regular && agentConfig.regular.file.length > 0){
    routerFileReadActions.push(loadRouter(agentConfig.regular));
  }else{
    console.log("%s项目没有找到任务路由...", path.basename(currentPath));
  }


  //等待promise完成后的操作（执行回调函数）
  Promise.all(routerFileReadActions).then(()=>{ // 调用Promise的all方法，传入方法数组，结束后执行then方法参数中的方法
    console.log("\r\n%s项目配置加载完毕", path.basename(currentPath));
    callback();
   });

  /**
   * 路由配置的加载操作
   * @param {router} 读取到的路由对象
   */
  function loadRouter(router){
    // console.log(path.join(currentPath,router.file));
    return new Promise(resolve => {
      SwaggerParser.validate(path.join(currentPath,router.file), function(err,api){
        if(!err){
          //获取路由配置，解析并加载
          parserLoadRouter(api,app,currentPath,routerConfig);
          resolve();
        }else{
          console.log(err);
        }
      });
    });
  }
}
